import {ref} from "vue";
import {DayReport} from "../sql/domin";
import {listReport} from "../api/report";
import {ReportMapper} from "../mappers/ReportMapper";
import {loginService} from "./login";
import {onLoad} from "@dcloudio/uni-app";

export function ReportDataHandle() {

    const {getNetWorkType} = loginService()

    const reports = ref<DayReport[]>()

    const refrashReport = async () => {
        let res = await listReport()
        let reports = res.data.data as DayReport[]
        await ReportMapper.deleteReportBefore30Day()
        let localReports = (await ReportMapper.selectReportList()) as DayReport[]
        let inserts: DayReport[] = []
        reports.forEach(it => {
            // @ts-ignore
            delete it.params
			delete it.userId
			delete it.createBy
            // 如果本地已存在则更新
            if (localReports.filter(i => i.id == it.id).length != 0) {
                ReportMapper.updateReport(it)
            } else {
                inserts.push(it)
            }
        })
        if (inserts.length != 0) {
            await ReportMapper.insertReport(inserts)
        }
        await getList()
    }

    const getList = async () => {
        reports.value = (await ReportMapper.selectReportList()) as DayReport[]
        //('101',reports.value)
    }

    getList()

    const content = [
        {
            iconPath: '/static/refrash.png',
            selectedIconPath: '/static/refrash-active.png',
            text: '刷新',
            active: false
        }
    ]

    const handleClick = async (e: any) => {

        uni.showToast({
            icon: 'none',
            title: '正在检查网络'
        })
        if (await getNetWorkType()) {
            uni.showLoading({
                title: '网络连接成功,正在拉取数据'
            })
            refrashReport().then(() => {
                getList()
            })
            uni.hideLoading()
        }


    }
    return {
        reports,
        refrashReport,
        handleClick,
        content
    }

}


export function ReportFormHandle(){

    const report = ref<DayReport>()

    onLoad(async (porps)=>{
        //(porps)
        let id = Number.parseInt(porps.id as string)
        report.value = ((await ReportMapper.selectReportById(id)) as DayReport[])[0]
    })

    return{
        report
    }
}
